package KharkovITCourses.proc.loop.array_merger_fixed;

/**
 * Created with IntelliJ IDEA.
 * User: ZefiR
 * Date: 02.01.13
 * Time: 10:33
 * To change this template use File | Settings | File Templates.
 */
public class Merger
{
    public static int[] merge(int[] a, int[] b) {
        int[] result = new int[a.length + b.length];
        int aIndex = 0;
        int bIndex = 0;
        while (aIndex + bIndex != result.length) {
            if (aIndex == a.length) {
                //result[bIndex + aIndex] = b[bIndex++];
                //continue;
                System.arraycopy(b, bIndex, result, bIndex + aIndex, b.length-bIndex);
                break;
            }
            if (bIndex == b.length) {
                //result[bIndex + aIndex] = a[aIndex++];
                //continue;
                System.arraycopy(a, aIndex, result, bIndex + aIndex, a.length-aIndex);
                break;
            }
            if (a[aIndex] < b[bIndex]) {
                result[aIndex + bIndex] = a[aIndex++];
            } else {
                result[aIndex + bIndex] = b[bIndex++];
            }
        }
        return result;
    }
}
